/**
 * Dropdown
 * @Author ace.ch
 * @Date 2018/1/24 18:04
 */
class Dropdown extends BaseSprite {

    //关闭其他相同组件
    static CLOSEOTHERS: string = 'DROPDOWN_OPENORCLOSE';
    //修改
    static CHANGED: string = 'DROPDOWN_CHANGED';

    private group: eui.Group;
    private scroller: eui.Scroller;
    private container: eui.Group;
    private btn_click: eui.Group;
    private value: eui.Image;

    sign: string;
    list: string[] = [];

    constructor() {
        super();

        this.skinName = "DropdownSkin";
    }

    childrenCreated() {
        super.childrenCreated();

        this.group.height = 205;

        this.sign = '' + Math.random();

        this.btn_click.addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickHandler, this);
        this.stage.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeHandler, this);

        gameManager.i.addEventListener(Dropdown.CLOSEOTHERS, this.closeothersHandler, this);
        gameManager.i.addEventListener(DropdownItem.SELECTED, this.selectedHandler, this);
    }

    private clickHandler(e: egret.TouchEvent) {
        e.stopImmediatePropagation();
        e.stopPropagation();

        if (this.skinState == 'open') {
            this.close();
        }
        else {
            this.open();
        }

        gameManager.i.dispatchEvent(Dropdown.CLOSEOTHERS, this.sign);
    }

    private closeothersHandler(sign: string) {
        if (sign != this.sign) {
            this.close();
        }
    }

    private closeHandler(e: egret.TouchEvent) {
        this.close();
    }

    private selectedHandler(data: any) {
        if (this.sign != data.sign) {
            return;
        }

        this.close();

        this.data = data;

        this.value.source = this.data.value;

        gameManager.i.dispatchEvent(Dropdown.CHANGED, this.sign);
    }

    private close() {
        this.skinState = 'close';

        this.scroller.stopAnimation();
        this.container.scrollV = 0;
        this.container.validateNow();
    }

    private open() {
        this.skinState = 'open';
    }

    update(list: string[]) {
        this.list = list;

        if (this.list && this.list.length) {

            let item: DropdownItem;
            for (let i: number = 0; i < this.list.length; i++) {
                item = new DropdownItem();
                item.sign = this.sign;
                this.container.addChild(item);

                item.data = this.list[i];
            }

            this.value.source = "" + this.list[0];
        }
    }

    get selectedValue() {
        return this.data ? this.data.value : '';
    }

    set selectedValue(v: string) {
        this.value.source = v;
    }

    get selectedIndex() {
        return this.list.indexOf(this.selectedValue);
    }

    set selectedIndex(v: number) {
        this.selectedValue = this.list[v];
    }
}